var _Pdf = function(){
  let handleText = (text,data)=>{
    if (typeof text == "string"){
      text = [text]
    }
    let result = [];
    $.each(text,(k,str)=>{
      result.push(str.format(data));
    });
    return result;
  };
  let getDoc = (cert)=>{
    let size = [cert.width,cert.height];
    var doc = new jsPDF({
      orientation: 'portrait',
      unit: 'pt',
      format: size
    });
    return doc
  };
  let drawImage = (doc,items) =>{
    items.forEach(item =>{
      console.info(item);
      doc.addImage(item.data, 'png', item["x"], item["y"], item["width"], item["height"]);
    })
  };
  let drawText = (doc,items,data)=>{
    items.forEach(item =>{
      doc.setFont(item.font ||"arial");
      // doc.setFontType(item.fontStyle || "normal")
      doc.setFontSize(item.fontSize || "20");
      doc.setTextColor(item.color || "#000000");
      if (item.options["lineHeightFactor"]){
        item.options["lineHeightFactor"] = parseFloat(item.options["lineHeightFactor"]);
      }
      doc.text(handleText(item.texts,data),item.x,item.y,item.options);
    });
  };
  let genPdf = (certId, certData,area,fileName,cb) => {
    _CertData.loadCert(certId, (cert) => {
      $.each(certData, (index, itemData) => {
        let doc = getDoc(cert);
        if (cert.picData){
          doc.addImage(cert.picData, 'png', 0, 0, cert.width,cert.height);
        }
        drawText(doc,cert.items,itemData);
        uploadCert(cert,itemData,doc.output("blob"),area,fileName,(path)=>{
          path ? cb(1,index+1,path) : cb(-1,index+1);
          (index+ 1) == certData.length && cb(0);
        });
      });
      
    })
  };
  let uploadCert = (cert,itemData,certBlob,area,fileName,cb) =>{
    itemData["AreaType"] = area=="all" ? "N":"R";
    itemData["CertName"] = cert.name;
    let pdfFileName = (fileName || "").format(itemData);
    // let certName = (area=="all" ? "N-":"R-")+ (fileName.trim() || cert.name+".pdf");
     // let name  = (area ? area + "/":"") + "cert/" + cert.name + "/";
     // name +=  itemData["TeamName"].trim() + "/" +certName;
     let name  = (area ? area + "/":"") + "cert/" + pdfFileName;
    console.info(name);
    upload("/upload", {
      "data": certBlob,
      "name": name
    }, (r) => cb(r),()=>cb(""))
  };
  
  return {
    getDoc,
    drawImage,
    drawText,
    genPdf
  }
}();
